package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollUtil;
import com.itheima.domain.mongo.*;
import com.itheima.service.mongo.MovementService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;


@DubboService
public class MovementServiceImpl implements MovementService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RedisIdService redisIdService;

    @Override
    public void save(Movement movement) {
        //0.获取用户id
        Long userId = movement.getUserId();

        //1.给动态设置pid,保存到动态详情表中
        movement.setPid(redisIdService.getNextId(ConstantUtil.MOVEMENT_ID));
        mongoTemplate.save(movement);

        //2.构造我的动态对象,保存到我的动态表中
        MyMovement myMovement = new MyMovement();
        myMovement.setPublishId(movement.getId());//设置动态id
        myMovement.setCreated(movement.getCreated());//设置时间

        //mongoTemplate.save(myMovement,"movement_mine_"+userId);
        mongoTemplate.save(myMovement,ConstantUtil.MOVEMENT_MINE+userId);

        //3.查询当前用户有哪些好友 list
        Query query = new Query(Criteria.where("userId").is(userId));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);

        //4.遍历集合获取每个好友id
        if (CollUtil.isNotEmpty(friends)) {
            friends.forEach(e->{
                //获取每个好友id
                Long friendId = e.getFriendId();

                //5.将动态放入好友的 好友动态表中
                FriendMovement friendMovement = new FriendMovement();
                friendMovement.setUserId(userId);//发布人
                friendMovement.setPublishId(movement.getId());//动态id
                friendMovement.setCreated(movement.getCreated());//发布时间

                mongoTemplate.save(friendMovement,ConstantUtil.MOVEMENT_FRIEND+friendId);
            });
        }

    }


    @Override
    public PageBeanVo findMyMovementByPage(Integer pageNum, Integer pageSize, Long userId) {
        //1.构造 条件查询对象(分页,排序)
        Query query = new Query().with(Sort.by(Sort.Order.desc("created"))).skip((pageNum-1)*pageSize).limit(pageSize);

        //2.查询 userId的我的动态表,获取动态id的集合
        List<MyMovement> myMovements = mongoTemplate.find(query, MyMovement.class, ConstantUtil.MOVEMENT_MINE + userId);

        //3.通过动态id查询动态详情表,获取每个动态详情
        //3.1 声明动态详情集合
        List<Movement> movementList = new ArrayList<>();

        //3.2 遍历老集合,查询动态详情,将详情放入动态详情集合中
        if (CollUtil.isNotEmpty(myMovements)) {
            myMovements.forEach(e->{
                //根据id查询动态详情表
                Movement movement = mongoTemplate.findById(e.getPublishId(), Movement.class);

                //放入动态集合
                movementList.add(movement);
            });
        }

        //4.封装pageBeanVo且返回
        //4.1 查询总记录数
        query = new Query();
        long count = mongoTemplate.count(query, ConstantUtil.MOVEMENT_MINE + userId);
        //4.2 返回pageBeanVo
        return new PageBeanVo(pageNum,pageSize,count,movementList);
    }

    @Override
    public PageBeanVo findFriendMovementByPage(Integer pageNum, Integer pageSize, Long userId) {
        //1.构造条件查询对象(分页和排序)
        Query query = new Query().with(Sort.by(Sort.Order.desc("created"))).skip((pageNum - 1) * pageSize).limit(pageSize);

        //2.查询userId的好友动态表,可以获取那些好友发布了那些动态(好友id和动态id)
        List<FriendMovement> friendMovements = mongoTemplate.find(query, FriendMovement.class, ConstantUtil.MOVEMENT_FRIEND + userId);

        //3.遍历好友动态集合,获取每个 好友动态,查询动态详情表,获取动态详情,将它放入一个详情表集合中
        //3.1 声明动态详情集合
        List<Movement> movementList = new ArrayList<>();

        //3.2 遍历好友动态集合,查询动态详情,将详情放入动态详情集合中
        if (CollUtil.isNotEmpty(friendMovements)) {
            friendMovements.forEach(e->{

                //查询动态详情,
                Movement movement = mongoTemplate.findById(e.getPublishId(), Movement.class);

                //将详情放入动态详情集合中
                movementList.add(movement);
            });
        }

        //4.封装pageBeanVo返回
        //4.1 查询总记录数
        query = new Query();
        long count = mongoTemplate.count(query, ConstantUtil.MOVEMENT_FRIEND + userId);
        //4.2 返回pageBeanVo
        return new PageBeanVo(pageNum,pageSize,count,movementList);
    }

    @Override
    public PageBeanVo findRecommendMovementByPage(Integer pageNum, Integer pageSize, Long userId) {
        //1.构造条件查询对象(分页和排序)
        Query query = new Query(
                Criteria.where("userId").is(userId)
        ).with(Sort.by(Sort.Order.desc("created"))).skip((pageNum - 1) * pageSize).limit(pageSize);

        //2.查询推荐动态表,可以获取那些那些动态(动态id)
        List<RecommendMovement> recommendMovements = mongoTemplate.find(query, RecommendMovement.class);


        //3.遍历推荐动态集合,获取每个 推荐动态,查询动态详情表,获取动态详情,将它放入一个详情表集合中
        //3.1 声明动态详情集合
        List<Movement> movementList = new ArrayList<>();

        //3.2 遍历推荐动态集合,查询动态详情,将详情放入动态详情集合中
        if (CollUtil.isNotEmpty(recommendMovements)) {
            recommendMovements.forEach(e->{

                //查询动态详情,
                Movement movement = mongoTemplate.findById(e.getPublishId(), Movement.class);

                //将详情放入动态详情集合中
                movementList.add(movement);
            });
        }

        //4.封装pageBeanVo返回
        //4.1 查询总记录数
        query = new Query(
                Criteria.where("userId").is(userId)
        );
        long count = mongoTemplate.count(query, RecommendMovement.class);
        //4.2 返回pageBeanVo
        return new PageBeanVo(pageNum,pageSize,count,movementList);
    }

    @Override
    public Movement findById(ObjectId publishId) {
        return mongoTemplate.findById(publishId,Movement.class);
    }

    @Override
    public PageBeanVo findByConditionAndPage(Long userId, Integer state, Integer pageNum, Integer pageSize) {
        //1.创建条件对象
        Query query = new Query();

        //2.判断userId是否为空,不为空则添加条件
        if (userId != null) {
            query.addCriteria(Criteria.where("userId").is(userId));
        }

        //3.判断state是否为空,不为空则添加条件
        if (state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }

        //4.先查询总记录数
        long count = mongoTemplate.count(query, Movement.class);

        //5.添加分页条件和排序条件
        query.with(Sort.by(Sort.Order.desc("created"))).skip((pageNum-1)*pageSize).limit(pageSize);

        //6.查询当前页数据
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);

        //7.封装PageBeanVo返回
        return new PageBeanVo(pageNum,pageSize,count,movementList);
    }

    @Override
    public void update(Movement movement) {
        mongoTemplate.save(movement);
    }
}
